package com.aihuishou.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author Zhang Jintao
 * @Date 2021/3/20 15:06
 * @Version 1.0
 */
@RestController
@Slf4j
@Api(tags = "消息生产者")
public class MessageProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    private static final String TOPIC = "queue_test";

    @GetMapping("sendMsg/{msg}")
    @ApiOperation("同步消息")
    public String sendMsg(@PathVariable("msg") String msg) {
        rocketMQTemplate.syncSend(TOPIC, MessageBuilder.withPayload(msg).build());
        return "ok";
    }

    @GetMapping("sendAsyncMsg/{msg}")
    @ApiOperation("异步消息")
    public String sendAsyncMsg(@PathVariable("msg")String msg) {
        rocketMQTemplate.asyncSend(TOPIC, MessageBuilder.withPayload(msg).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("SUCCESS");
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("ERROR...", throwable);
            }
        });
        return "ok";
    }

    @GetMapping("sendDelayMsg/{msg}")
    @ApiOperation("延迟消息")
    public String sendDelayMsg(@PathVariable("msg")String msg) {
        rocketMQTemplate.syncSend(TOPIC, MessageBuilder.withPayload(msg).build(), 2000, 3);
        return "ok";
    }

    @GetMapping("sendTagMsg/{msg}")
    @ApiOperation("标签消息")
    public String sendTagMsg(@PathVariable("msg")String msg) {
        rocketMQTemplate.syncSend(TOPIC + ":tag1", MessageBuilder.withPayload(msg).build());


        return "ok";
    }
}
